﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;

namespace Game.Setting
{
	/// <summary>
	/// Handles the events on quality changes & Music & Sound FX
    /// <para>负责质量设定、音乐、音效等</para>
    /// <para>ps:画面图形质量等级将以已有的Toggle映射到对应的质量等级上</para>
	/// </summary>
	public abstract class GameSettingsBase :MonoBehaviour
	{
		/// <summary>
		/// Occurs when quality changed.
		/// </summary>
		event CallbackFuncWithInt m_eventOnQualityChanged;

		#region public part
		/// <summary>
		/// Add Listener on setting changing event.
		/// </summary>
		/// <param name="callbackWithQualityLevel">Callback with quality level.</param>
		public void AddOnSettingChange(CallbackFuncWithInt callbackWithQualityLevel)
		{
			m_eventOnQualityChanged += callbackWithQualityLevel;
		}

        public int GetQualityLevelCount()
        {
            return QualitySettings.names.Length;   
        }
        #endregion

        #region Sound & FX
        public enum AUDIOTYPE
        {
            /// <summary>
            /// 跳动声
            /// </summary>
            JUMP_SOUND,

            /// <summary>
            /// 截屏声
            /// </summary>
            CAPTURE_SCREEN,

            /// <summary>
            /// 怪物攻击声
            /// </summary>
            MONSTER_ATTACK,

            /// <summary>
            /// 英雄攻击声
            /// </summary>
            HERO_ATTACK,

            /// <summary>
            /// 获得硬币、金钱的声音
            /// </summary>
            GET_ITEM,

            /// <summary>
            /// 带上东西的声音
            /// </summary>
            CARRY_THING_UP,

            /// <summary>
            /// 吃的声音
            /// </summary>
            EAT_Sth,

            /// <summary>
            /// 游戏结束时声
            /// </summary>
            GAME_OVER,

            /// <summary>
            /// 发射子弹等
            /// </summary>
            SHOOT_SOUND,
        };


        protected AudioSource m_audioSource;

        //****************************************************************************************************
        //		Some clips are here, some are not for the player and the enemy has an static clip that didn't 
        //need to storage in its member variable.
        //****************************************************************************************************
        [Tooltip("在调试时，是否播放声音")][SerializeField] bool m_DebugWithSound = false;
        [SerializeField] AudioClip m_audioBGM;                                        //background music.

        [SerializeField] AudioClip m_audioJump;
        [SerializeField] AudioClip m_audioMonsterAttack;
        [SerializeField] AudioClip m_audioHeroAttack;
        [SerializeField] AudioClip m_audioGetItem;
        [SerializeField] AudioClip m_audioFeedFood;                                //喂养
        [SerializeField] AudioClip m_audioCarryUp;                                     //带上东西
        [SerializeField] AudioClip m_audioGameOver;
        [SerializeField] AudioClip m_audioShoot;                                      //射击子弹

        [SerializeField] AudioClip m_audioCaptureScreen;                              //The bird was defended.

        // Use this for initialization
        protected void InitSound()
        {
            if (!this.GetComponent<AudioSource>())
                this.gameObject.AddComponent<AudioSource>();
            m_audioSource = this.GetComponent<AudioSource>();

            if (m_audioBGM)
            {
                //Play the background music if have one
                m_audioSource.clip = m_audioBGM;
                m_audioSource.loop = true;
                m_audioSource.Play();
            }

        }


        //float lastPlaySoundTime = -99F;
        public void PlayAudio(AUDIOTYPE audioType)
        {
#if UNITY_EDITOR
            if(!m_DebugWithSound)
            {
                return;
            }
#endif
            if (isMusicOn)
            {
                switch (audioType)
                {
                    case AUDIOTYPE.GET_ITEM:
                        m_audioSource.PlayOneShot(m_audioGetItem);
                        break;

                    case AUDIOTYPE.EAT_Sth:
                        m_audioSource.PlayOneShot(m_audioFeedFood);
                        break;

                    case AUDIOTYPE.CARRY_THING_UP:
                        m_audioSource.PlayOneShot(m_audioCarryUp);
                        break;

                    case AUDIOTYPE.HERO_ATTACK:
                        m_audioSource.PlayOneShot(m_audioHeroAttack);
                        break;

                    case AUDIOTYPE.JUMP_SOUND:
                        m_audioSource.PlayOneShot(m_audioJump);
                        break;

                    case AUDIOTYPE.MONSTER_ATTACK:
                        m_audioSource.PlayOneShot(m_audioMonsterAttack);
                        break;

                    case AUDIOTYPE.GAME_OVER:
                        m_audioSource.PlayOneShot(m_audioGameOver);
                        break;

                    case AUDIOTYPE.CAPTURE_SCREEN:
                        m_audioSource.PlayOneShot(m_audioCaptureScreen);
                        break;

                    case AUDIOTYPE.SHOOT_SOUND:
                        m_audioSource.PlayOneShot(m_audioShoot);
                        break;
                    default:
                        //新注释的Debug.LogError("try to play an undefine music !");
                        break;
                }
            }
        }

        bool isMusicOn = true;
        public void TurnMusicTo(bool isOn)
        {
            isMusicOn = isOn;

            if (isOn)
            {
                if (!m_audioSource.isPlaying)
                {
                    m_audioSource.Play();
                }
            }
            else
            {
                if (m_audioSource.isPlaying)
                {
                    m_audioSource.Stop();
                }
            }
        }

        public bool IsPlayingBGM()
        {
            return m_audioSource.isPlaying;
        }
        #endregion


        #region UI part

        /// <summary>
        /// 初始化图形质量选项
        /// </summary>
        protected void InitQualityGroup(ToggleGroup toggleGroupGameSetting = null)
		{
			if(toggleGroupGameSetting == null)
			{
				Debug.Log("No toggle group for game setting found");
				return;
			}

            //根据已有的Toggle，决定到对应的等级上
			Toggle[] allQualityToggles = toggleGroupGameSetting.GetComponentsInChildren<Toggle>();
			Toggle toggle = null;
            int toggleCount = allQualityToggles.Length;
            int qualityCount = GetQualityLevelCount();

            //--检查
            if (toggleCount <= 0)
            {
                Debug.LogWarning("Maybe you have forgot to switch the toggles on.");
            }

			for( int i = 0 ; i < toggleCount ; i++)
			{
				toggle = allQualityToggles[i];

				int toggleIndex = i;
				toggle.onValueChanged.AddListener(
					(isOn)=>
					{
						if(isOn)
						{
                            //通过现有的按钮映射到对应的质量等级上：
                            int toQualityLevel = (toggleIndex + 1) * qualityCount / toggleCount - 1;
							Debug.Log ("Switch game setting to :"+toQualityLevel);
							SetGameQualityLevel(toQualityLevel);
						}
					});
			}


		}

		/// <summary>
		/// Changes the setting.
		/// </summary>
		/// <param name="qualityLevel">Quality level.</param>
		private void SetGameQualityLevel(int qualityLevel)
		{
			QualitySettings.SetQualityLevel((int)qualityLevel);
			
			//Callback to notify those subscribers.
			if(m_eventOnQualityChanged!=null)
			{
				m_eventOnQualityChanged(qualityLevel);
			}
		}
		#endregion
	}
}